package org.elanfox.intellicommunity.intellicommunityadmin.init;

import org.elanfox.intellicommunity.biz.dto.redis.RedisCardDTO;
import org.elanfox.intellicommunity.biz.dto.redis.RedisRoomDTO;
import org.elanfox.intellicommunity.biz.dto.redis.RedisUserDTO;
import org.elanfox.intellicommunity.biz.entity.equipment.CardPO;
import org.elanfox.intellicommunity.biz.entity.resident.RoomPO;
import org.elanfox.intellicommunity.biz.entity.resident.UserPO;
import org.elanfox.intellicommunity.biz.repository.equipment.CardRepository;
import org.elanfox.intellicommunity.biz.repository.resident.RoomRepository;
import org.elanfox.intellicommunity.biz.repository.resident.UserRepository;
import org.elanfox.intellicommunity.common.constant.RedisConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Auther: loutianxi
 * @Date: 2021/2/4 12:10
 * @Description:
 */
@Component
public class InitRedisData {
    @Autowired
    private CardRepository cardService;
    @Autowired
    private UserRepository userService;
    @Autowired
    private RoomRepository roomService;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @PostConstruct
    public void initRedis() {
        initUser();
        initCard();
        initRoom();
    }


    @Scheduled(cron = "0 0 */5 * * ?")
    public void initUser() {
        //初始化用户
        List<UserPO> userPOS = userService.findByDelFlagIsTrue();
        Map<String, RedisUserDTO> userMap = new HashMap<>();
        for (UserPO user : userPOS) {
            userMap.put("user_" + user.getUserId(), new RedisUserDTO(user));
        }
        redisTemplate.opsForHash().putAll(RedisConstant.KEY_USER, userMap);
    }

    //初始化工卡
    @Scheduled(cron = "0 0 */5 * * ?")
    public void initCard() {
        List<CardPO> cardPOS = cardService.findByDeleteStatusIsFalse();
        Map<String, RedisCardDTO> cardMap = new HashMap<>();
        for (CardPO cardPO : cardPOS) {
            cardMap.put("card_" + cardPO.getCardNo(), new RedisCardDTO(cardPO));
        }
        redisTemplate.opsForHash().putAll(RedisConstant.KEY_CARD, cardMap);
    }

    //初始化房间
    @Scheduled(cron = "0 0 */5 * * ?")
    public void initRoom() {
        List<RoomPO> roomPOS = roomService.findByDelFlagIsTrue();
        Map<String, RedisRoomDTO> roomMap = new HashMap<>();
        for (RoomPO room : roomPOS) {
            roomMap.put("room_" + room.getRoomName(), new RedisRoomDTO(room));
        }
        redisTemplate.opsForHash().putAll(RedisConstant.KEY_ROOM, roomMap);
    }
}
